-- SkyIslandM
-- Create by dengc
-- 天空之城浮岛模块

module("SkyIslandM", package.seeall);

-- 浮岛配置表
local skyIslandConfigTable = {};

-- 浮岛元素表
local skyIslandElementTable = {};

-- 模块初始化
function init()
    local sky_island_config_csv = get_sky_island_config_CSV();
    for i = 1, #sky_island_config_csv do
        local name = sky_island_config_csv[i].name;
        skyIslandConfigTable[name] = sky_island_config_csv[i];
    end

    local sky_island_element_csv = get_sky_island_element_CSV();
    for i = 1, #sky_island_element_csv do
        local id = sky_island_element_csv[i].id;
        skyIslandElementTable[id] = sky_island_element_csv[i];
    end

    sky_island_config_csv = {};
    sky_island_element_csv = {};
end

-- 检索浮岛配置
function queryConfig(name, path)
    local m = skyIslandConfigTable[name];
    if not m or path == "" or not path then
        return m;
    else
        return m[path];
    end
end

-- 检索浮岛元素
function queryElement(id, path)
    local m = skyIslandElementTable[id];
    if not m or path == "" or not path then
        return m;
    else
        return m[path];
    end
end

-- 根据浮岛名称，生成浮岛配置
-- 传入type会生成固定的配置，不做随机
function initIslandByName(name, islandType)
    local elementsList = queryConfig(name, "elements");

    -- 不符合规范，返回
    if type(elementsList) ~= "table" or #elementsList == 0 then
        return nil;
    end

    -- 生成随机或固定的浮岛配置
    local elements;
    local curType;
    if not islandType then
        local total = #elementsList;
        curType = math.random(1, total);
        elements = elementsList[curType];
    else
        curType = islandType;
        elements = elementsList[curType];
    end

    if not elements then
        elements = elementsList[1];
    end

    -- 生成配置
    local config = {};
    for _, element in pairs(elements) do
        local offset = queryElement(element, "offset");
        table.insert(config, {
            ["icon"]    = queryElement(element, "icon"),
            ["node"]    = queryElement(element, "node"),
            ["layer"]   = queryElement(element, "layer"),
            ["scale"]   = queryElement(element, "scale"),
            ["opacity"] = queryElement(element, "opacity"),
            ["offset"]  = type(offset) == "table" and offset or {0, 0},
        });
    end

    return config, curType;
end
